package com.example.lets;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bmob.BTPFileResponse;
import com.bmob.BmobPro;
import com.bmob.BmobProFile;
import com.bmob.btp.callback.DownloadListener;
import com.bmob.btp.callback.LocalThumbnailListener;
import com.gc.materialdesign.views.ButtonFloat;
import com.gc.materialdesign.views.ButtonRectangle;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ScrollState;
import com.github.ksoichiro.android.observablescrollview.ScrollUtils;
import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;
import com.widget.CircleImageView;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.bmob.v3.BmobObject;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.DeleteListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class EventActivity extends BaseActivity implements ObservableScrollViewCallbacks {

    private ImageView mImageView;
    private View mOverlayView;
    private View mListBackgroundView;
    private View mFab;
    private PullableListView listView;
    private ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();

    private CommentAdapter adapter;
    private int mActionBarSize;
    private int mFlexibleSpaceShowFabOffset;
    private int mFlexibleSpaceImageHeight;
    private int mFabMargin;
    private boolean mFabIsShown;
    private int page = 0;
    private View paddingView, eventHeader;

    public static double scrollY;
    public static boolean isBottom;
    public static boolean hasNew = false;
    private String ActiId;
    private boolean hasGrade = false;
    private boolean canGrade = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event);

        mFlexibleSpaceImageHeight = getResources().getDimensionPixelSize(R.dimen.flexible_space_image_height);
        mFlexibleSpaceShowFabOffset = getResources().getDimensionPixelSize(R.dimen.flexible_space_show_fab_offset);
        mActionBarSize = getActionBarSize();
        mImageView = (ImageView) findViewById(R.id.type_image);
        mOverlayView = findViewById(R.id.overlay);
        ViewHelper.setAlpha(mOverlayView, 0.0f);
        listView = (PullableListView) findViewById(R.id.event_list);
        listView.setScrollViewCallbacks(this);
        listView.setHeaderDividersEnabled(false);

        // Set padding view for ListView. This is the flexible space.
        paddingView = new View(this);
        AbsListView.LayoutParams lp = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
                mFlexibleSpaceImageHeight - mActionBarSize);
        paddingView.setLayoutParams(lp);

        // This is required to disable header's list selector effect
        paddingView.setClickable(true);

        listView.addHeaderView(paddingView);
        mFab = findViewById(R.id.fab);
        mFabMargin = getResources().getDimensionPixelSize(R.dimen.margin_standard);
        ViewHelper.setScaleX(mFab, 0);
        ViewHelper.setScaleY(mFab, 0);

        // mListBackgroundView makes ListView's background except header view.
        mListBackgroundView = findViewById(R.id.list_background);

        // load event header
        final LayoutInflater inflater = getLayoutInflater();
        eventHeader = inflater.inflate(R.layout.event_header, null);
        listView.addHeaderView(eventHeader);

        // original codes starts here
        final Intent in = getIntent();
        final String description = in.getStringExtra("description");
        final String PicfileName = in.getStringExtra("picFileName");
        final String sponsorId = in.getStringExtra("sponsorId");
        final String type = in.getStringExtra("type");
        ActiId = in.getStringExtra("id");

        // toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.event_toolbar);
        toolbar.setTitle(null);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        //edit activity
        final ButtonRectangle editInfo = (ButtonRectangle) findViewById(R.id.event_full_info_edit);
        editInfo.setBackgroundColor(Color.parseColor("#E51C23"));
        if (sponsorId.equals(BmobUser.getCurrentUser(EventActivity.this).getObjectId())) {
            editInfo.setVisibility(View.VISIBLE);
        } else {
            editInfo.setVisibility(View.INVISIBLE);
        }
        editInfo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Intent intent = new Intent(EventActivity.this, InitiateEventActivity.class);
                intent.putExtra("mode", "edit");
                intent.putExtra("title", "编辑活动");
                intent.putExtra("name", in.getStringExtra("title"));
                intent.putExtra("description", description);
                intent.putExtra("picFileName", PicfileName);
                intent.putExtra("sponsorId", sponsorId);
                intent.putExtra("place", in.getStringExtra("place"));
                intent.putExtra("detail", in.getStringExtra("detail"));
                intent.putExtra("time", in.getStringExtra("time"));
                intent.putExtra("type", type);
                intent.putExtra("id", ActiId);
                startActivity(intent);
                EventActivity.this.finish();
            }
        });


        //load grade here
        final TextView mRatingText = (TextView) findViewById(R.id.ratingText);
        final RatingBar mRatingBar = (RatingBar) findViewById(R.id.ratingBar);
        final ButtonRectangle ratingConfirm = (ButtonRectangle) findViewById(R.id.rating_button);
        ratingConfirm.setBackgroundColor(Color.parseColor("#E51C23"));

        mRatingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {

            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean b) {
                // final int numStars = ratingBar.getNumStars();
                if (ratingConfirm.getVisibility() == View.VISIBLE)
                    mRatingText.setText("您给出的分数为：" + rating + "/5.0");
                else {
                    DecimalFormat formater = new DecimalFormat("0.0");
                    mRatingText.setText("本活动评分为：" + formater.format(rating) + "/5.0");
                }
                if (ratingBar.getRating() != rating) {
                    mRatingBar.setRating(rating);
                }
            }
        });

        ratingConfirm.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Grade grade = new Grade();
                grade.setActivityId(ActiId);
                grade.setScore(new Double(mRatingBar.getRating()));
                grade.setUserId(BmobUser.getCurrentUser(EventActivity.this).getObjectId());
                grade.save(EventActivity.this, new SaveListener() {

                    @Override
                    public void onSuccess() {
                        ratingConfirm.setVisibility(View.INVISIBLE);
                        mRatingBar.setIsIndicator(true);
                        BmobQuery<Grade> query = new BmobQuery<Grade>();
                        query.addWhereEqualTo("activityId", ActiId);
                        query.findObjects(EventActivity.this, new FindListener<Grade>() {

                            @Override
                            public void onSuccess(List<Grade> list) {
                                double score = 0;
                                for (Grade object : list) {
                                    score += object.getScore();
                                }
                                score /= list.size();

                                DecimalFormat formater = new DecimalFormat("0.0");
                                mRatingText.setText("本活动评分为：" + formater.format(score) + "/5.0");
                                mRatingBar.setRating((float) score);
                            }

                            @Override
                            public void onError(int i, String s) {
                                Toast.makeText(EventActivity.this, "评分失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onFailure(int i, String s) {
                        Toast.makeText(EventActivity.this, "评分失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        BmobQuery<Involvement> query2 = new BmobQuery<Involvement>();
        query2.addWhereEqualTo("activityId", ActiId);
        query2.addWhereEqualTo("userId", BmobUser.getCurrentUser(EventActivity.this).getObjectId());
        query2.findObjects(EventActivity.this, new FindListener<Involvement>() {

            @Override
            public void onSuccess(List<Involvement> list) {
                if (list.size() > 0) {
                    canGrade = true;
                }
                // 此处查询评分，并检查是否有权限评分
                BmobQuery<Grade> query = new BmobQuery<Grade>();
                query.addWhereEqualTo("activityId", ActiId);
                query.findObjects(EventActivity.this, new FindListener<Grade>() {

                    @Override
                    public void onSuccess(List<Grade> list) {

                        double score = 0;
                        if (canGrade) {
                            if (list.size() == 0) {
                                mRatingText.setText("请为本活动评分：");
                                ratingConfirm.setVisibility(View.VISIBLE);
                                mRatingBar.setIsIndicator(false);
                            } else {
                                for (Grade object : list) {
                                    score += object.getScore();
                                    if (object.getUserId().equals(BmobUser.getCurrentUser(EventActivity.this).getObjectId())) {
                                        hasGrade = true;
                                    }
                                }
                                score /= list.size();
                                if (hasGrade) {
                                    ratingConfirm.setVisibility(View.INVISIBLE);
                                    mRatingBar.setIsIndicator(true);
                                    DecimalFormat formater = new DecimalFormat("0.0");
                                    mRatingText.setText("本活动评分为：" + formater.format(score) + "/5.0");
                                    mRatingBar.setRating((float) score);
                                } else {
                                    mRatingText.setText("请为本活动评分：");
                                    ratingConfirm.setVisibility(View.VISIBLE);
                                    mRatingBar.setIsIndicator(false);
                                }
                            }
                        } else {
                            ratingConfirm.setVisibility(View.INVISIBLE);
                            mRatingBar.setIsIndicator(true);
                            if (list.size() == 0) {
                                mRatingText.setText("本活动还没有人进行评分");
                                mRatingBar.setRating((float) 0);
                            } else {
                                for (Grade object : list) {
                                    score += object.getScore();
                                }
                                score /= list.size();
                                DecimalFormat formater = new DecimalFormat("0.0");
                                mRatingText.setText("本活动评分为：" + formater.format(score) + "/5.0");
                                mRatingBar.setRating((float) score);
                            }
                        }
                    }

                    @Override
                    public void onError(int i, String s) {
                        Toast.makeText(EventActivity.this, "查询评分失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onError(int i, String s) {

            }
        });

        listItem = new ArrayList<>();
        adapter = new CommentAdapter(this, listItem);
        listView.setAdapter(adapter);

        // comment send button
        Button sendBtn = (Button) findViewById(R.id.event_comment_button);
        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EditText commentText = (EditText) findViewById(R.id.event_comment_text);
                if (commentText.getText().toString().equals(""))
                    Toast.makeText(EventActivity.this, "请输入评论内容", Toast.LENGTH_SHORT).show();
                else {
                    final Comment comment = new Comment();
                    comment.setActivityId(getIntent().getStringExtra("id"));
                    comment.setContent(commentText.getText().toString());
                    comment.setUser(BmobUser.getCurrentUser(EventActivity.this, User.class));
                    comment.save(EventActivity.this, new SaveListener() {
                        @Override
                        public void onSuccess() {

                            BmobQuery<User> query = new BmobQuery<>();
                            query.getObject(EventActivity.this,
                                    BmobUser.getCurrentUser(EventActivity.this).getObjectId(),
                                    new GetListener<User>() {
                                        @Override
                                        public void onSuccess(User user) {
                                            Toast.makeText(EventActivity.this, "评论成功", Toast.LENGTH_SHORT).show();
                                            HashMap<String, Object> map = new HashMap<String, Object>();
                                            map.put("comment", comment);
                                            map.put("user", user);

                                            listItem.add(0, map);
                                            adapter.notifyDataSetChanged();

                                            listView.smoothScrollToPosition(0);
                                        }

                                        @Override
                                        public void onFailure(int i, String s) {

                                        }
                                    });
                        }

                        @Override
                        public void onFailure(int i, String s) {
                            Toast.makeText(EventActivity.this, "评论失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                // 收起键盘
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(commentText.getWindowToken(), 0);
                commentText.setText("");
            }
        });


        TextView vDescription = (TextView) eventHeader.findViewById(R.id.event_full_info_description);
        vDescription.setHint("");
        vDescription.setText(description);


        // Float button
        final ButtonFloat joinButton = (ButtonFloat) mFab;
        joinButton.setRippleSpeed(10.0f);
        // set icon
        final ImageView imageView = new ImageView(EventActivity.this);
        Drawable drawable = getResources().getDrawable(R.drawable.initiate_event_button);
        imageView.setImageDrawable(drawable);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
        imageView.setLayoutParams(params);
        joinButton.addView(imageView);
        joinButton.setBackgroundColor(Color.parseColor("#E51C23"));

        // delete and quit icon
        final ImageView quit = new ImageView(EventActivity.this);
        Drawable drawable_quit = getResources().getDrawable(R.drawable.remove_white_24dp);
        quit.setImageDrawable(drawable_quit);
        quit.setLayoutParams(params);

        final User curUser = BmobUser.getCurrentUser(EventActivity.this, User.class);
        final String userId = curUser.getObjectId();
        BmobQuery<Involvement> query1 = new BmobQuery<Involvement>();
        query1.addWhereEqualTo("activityId", ActiId);
        query1.addWhereEqualTo("userId", userId);
        query1.setLimit(100);
        query1.findObjects(EventActivity.this, new FindListener<Involvement>() {

            @Override
            public void onSuccess(List<Involvement> list) {
                if (list.size() > 0) {
                    //删除活动和退出活动时使用下面的代码
                    joinButton.removeAllViews();
                    joinButton.addView(quit);
                    joinButton.setBackgroundColor(Color.parseColor("#3F51B5")); // blue
                } else {
                    // 加入活动时使用下面的代码
                    joinButton.removeAllViews();
                    joinButton.addView(imageView);
                    joinButton.setBackgroundColor(Color.parseColor("#E51C23")); // red
                }
            }

            @Override
            public void onError(int i, String s) {
                Toast.makeText(EventActivity.this, "网络连接失败！", Toast.LENGTH_SHORT).show();
                Log.i("bmob", "查询失败！");
            }
        });

        joinButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                BmobQuery<Involvement> query = new BmobQuery<Involvement>();
                query.addWhereEqualTo("activityId", ActiId);
                query.addWhereEqualTo("userId", userId);
                query.setLimit(100);
                query.findObjects(EventActivity.this, new FindListener<Involvement>() {
                    @Override
                    public void onSuccess(final List<Involvement> list) {
                        if (list.size() > 0) {
                            if (userId.equals(sponsorId)) {
                                new AlertDialog.Builder(EventActivity.this).setTitle("删除活动")
                                        .setMessage("若删除活动则所有与活动相关的记录都会被删除，\n你确定要删除本活动吗？")
                                        .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                BmobQuery<Involvement> qi = new BmobQuery<Involvement>();
                                                qi.addWhereEqualTo("activityId", ActiId);
                                                qi.setLimit(50);
                                                qi.findObjects(EventActivity.this, new FindListener<Involvement>() {

                                                    @Override
                                                    public void onSuccess(List<Involvement> list) {
                                                        List<BmobObject> objects = new ArrayList<BmobObject>();
                                                        for (Involvement involvement : list) {
                                                            objects.add(involvement);
                                                        }
                                                        new BmobObject().deleteBatch(EventActivity.this, objects, new DeleteListener() {

                                                            @Override
                                                            public void onSuccess() {
                                                                BmobQuery<Comment> qc = new BmobQuery<Comment>();
                                                                qc.addWhereEqualTo("activityId", ActiId);
                                                                qc.setLimit(50);
                                                                qc.findObjects(EventActivity.this, new FindListener<Comment>() {

                                                                    @Override
                                                                    public void onSuccess(List<Comment> list) {
                                                                        List<BmobObject> objects = new ArrayList<BmobObject>();
                                                                        for (Comment comment : list) {
                                                                            objects.add(comment);
                                                                        }
                                                                        new BmobObject().deleteBatch(EventActivity.this, objects, new DeleteListener() {

                                                                            @Override
                                                                            public void onSuccess() {
                                                                                BmobQuery<Grade> qg = new BmobQuery<Grade>();
                                                                                qg.addWhereEqualTo("activityId", ActiId);
                                                                                qg.setLimit(50);
                                                                                qg.findObjects(EventActivity.this, new FindListener<Grade>() {

                                                                                    @Override
                                                                                    public void onSuccess(List<Grade> list) {
                                                                                        List<BmobObject> objects = new ArrayList<BmobObject>();
                                                                                        for (Grade grade : list) {
                                                                                            objects.add(grade);
                                                                                        }
                                                                                        new BmobObject().deleteBatch(EventActivity.this, objects, new DeleteListener() {

                                                                                            @Override
                                                                                            public void onSuccess() {
                                                                                                UserActivity userActivity = new UserActivity();
                                                                                                userActivity.setObjectId(ActiId);
                                                                                                userActivity.delete(EventActivity.this, new DeleteListener() {

                                                                                                    @Override
                                                                                                    public void onSuccess() {
                                                                                                        Toast.makeText(EventActivity.this, "删除活动成功！", Toast.LENGTH_SHORT).show();
                                                                                                        Log.i("bmob", "删除活动成功！");
                                                                                                        Intent intent = new Intent();
                                                                                                        intent.setClass(EventActivity.this, HomeActivity.class);
                                                                                                        startActivity(intent);
                                                                                                        EventActivity.this.finish();
                                                                                                    }

                                                                                                    @Override
                                                                                                    public void onFailure(int i, String s) {
                                                                                                        Toast.makeText(EventActivity.this, "删除活动失败！", Toast.LENGTH_SHORT).show();
                                                                                                        Log.i("bmob", "删除活动失败！");
                                                                                                    }
                                                                                                });
                                                                                            }

                                                                                            @Override
                                                                                            public void onFailure(int i, String s) {
                                                                                                Toast.makeText(EventActivity.this, "删除活动失败！", Toast.LENGTH_SHORT).show();
                                                                                                Log.i("bmob", "删除活动失败！");
                                                                                            }
                                                                                        });
                                                                                    }

                                                                                    @Override
                                                                                    public void onError(int i, String s) {
                                                                                        Toast.makeText(EventActivity.this, "删除活动失败！", Toast.LENGTH_SHORT).show();
                                                                                        Log.i("bmob", "删除活动失败！");
                                                                                    }
                                                                                });
                                                                            }

                                                                            @Override
                                                                            public void onFailure(int i, String s) {
                                                                                Toast.makeText(EventActivity.this, "删除活动失败！", Toast.LENGTH_SHORT).show();
                                                                                Log.i("bmob", "删除活动失败！");
                                                                            }
                                                                        });
                                                                    }

                                                                    @Override
                                                                    public void onError(int i, String s) {
                                                                        Toast.makeText(EventActivity.this, "删除活动失败！", Toast.LENGTH_SHORT).show();
                                                                        Log.i("bmob", "删除活动失败！");
                                                                    }
                                                                });
                                                            }

                                                            @Override
                                                            public void onFailure(int i, String s) {
                                                                Toast.makeText(EventActivity.this, "删除活动失败！", Toast.LENGTH_SHORT).show();
                                                                Log.i("bmob", "删除活动失败！");
                                                            }
                                                        });
                                                    }

                                                    @Override
                                                    public void onError(int i, String s) {
                                                        Toast.makeText(EventActivity.this, "删除活动失败！", Toast.LENGTH_SHORT).show();
                                                        Log.i("bmob", "删除活动失败！");
                                                    }
                                                });
                                            }
                                        })
                                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {

                                            }
                                        })
                                        .show();
                            } else {
                                new AlertDialog.Builder(EventActivity.this).setTitle("退出活动")
                                        .setMessage("你确定要退出本活动吗？")
                                        .setPositiveButton("退出", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                Involvement involvement = new Involvement();
                                                involvement.setObjectId(list.get(0).getObjectId());
                                                involvement.delete(EventActivity.this, new DeleteListener() {

                                                    @Override
                                                    public void onSuccess() {
                                                        UserActivity userActivity = new UserActivity();
                                                        userActivity.setObjectId(ActiId);
                                                        userActivity.increment("peopleNumber", -1);
                                                        userActivity.update(EventActivity.this, new UpdateListener() {

                                                            @Override
                                                            public void onSuccess() {
                                                                Toast.makeText(EventActivity.this, "已经退出活动！", Toast.LENGTH_SHORT).show();
                                                                Log.i("bmob", "退出活动成功");
                                                                Intent intent = new Intent();
                                                                intent.setClass(EventActivity.this, HomeActivity.class);
                                                                startActivity(intent);
                                                                EventActivity.this.finish();
                                                            }

                                                            @Override
                                                            public void onFailure(int i, String s) {
                                                                Toast.makeText(EventActivity.this, "退出活动失败！", Toast.LENGTH_SHORT).show();
                                                                Log.i("bmob", "退出活动失败");
                                                            }
                                                        });
                                                    }

                                                    @Override
                                                    public void onFailure(int i, String s) {
                                                        Toast.makeText(EventActivity.this, "退出活动失败！", Toast.LENGTH_SHORT).show();
                                                        Log.i("bmob", "退出活动失败");
                                                    }
                                                });
                                            }
                                        })
                                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {

                                            }
                                        })
                                        .show();
                            }
                        } else {
                            Involvement record = new Involvement();
                            record.setActivityId(ActiId);
                            record.setSponsorId(sponsorId);
                            record.setUserId(userId);
                            record.setUser(curUser);
                            record.save(EventActivity.this, new SaveListener() {

                                @Override
                                public void onSuccess() {
                                    UserActivity userActivity = new UserActivity();
                                    userActivity.setObjectId(ActiId);
                                    userActivity.increment("peopleNumber", 1);
                                    userActivity.update(EventActivity.this, new UpdateListener() {

                                        @Override
                                        public void onSuccess() {
                                            if (curUser.getJoinnum() == null) {
                                                curUser.setJoinnum(1);
                                            } else {
                                                curUser.setJoinnum(curUser.getJoinnum() + 1);
                                            }
                                            curUser.update(EventActivity.this, new UpdateListener() {

                                                @Override
                                                public void onSuccess() {
                                                    Toast.makeText(EventActivity.this, "活动加入成功！", Toast.LENGTH_SHORT).show();
                                                    Log.i("bmob", "加入活动成功！");
                                                    Intent intent = new Intent();
                                                    intent.setClass(EventActivity.this, HomeActivity.class);
                                                    startActivity(intent);
                                                    EventActivity.this.finish();
                                                }

                                                @Override
                                                public void onFailure(int i, String s) {
                                                    Toast.makeText(EventActivity.this, "加入活动失败！", Toast.LENGTH_SHORT).show();
                                                    Log.i("bmob", "加入活动失败！");
                                                }
                                            });
                                        }

                                        @Override
                                        public void onFailure(int i, String s) {
                                            Toast.makeText(EventActivity.this, "加入活动失败！", Toast.LENGTH_SHORT).show();
                                            Log.i("bmob", "加入活动失败！");
                                        }
                                    });
                                }

                                @Override
                                public void onFailure(int arg0, String arg1) {
                                    Toast.makeText(EventActivity.this, "加入活动失败！", Toast.LENGTH_SHORT).show();
                                    Log.i("bmob", "加入活动失败！");
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(int i, String s) {
                        Toast.makeText(EventActivity.this, "网络连接失败！", Toast.LENGTH_SHORT).show();
                        Log.i("bmob", "点击fab失败！");
                    }
                });
            }
        });

        final TextView sponsor = (TextView) eventHeader.findViewById(R.id.event_full_info_sponsor);
        final String id = in.getStringExtra("sponsorId");
        BmobQuery<User> q = new BmobQuery<User>();
        q.addWhereEqualTo("objectId", id);
        q.findObjects(EventActivity.this, new FindListener<User>() {

            @Override
            public void onError(int arg0, String arg1) {

            }

            @Override
            public void onSuccess(List<User> result) {
                String sponsorName = result.get(0).getNickname();
                sponsor.setText(sponsorName);
            }

        });

        TextView title = (TextView) findViewById(R.id.event_title);
        title.setText(getIntent().getStringExtra("title"));

        TextView time = (TextView) eventHeader.findViewById(R.id.event_full_info_date);
        time.setText(in.getStringExtra("time"));

        TextView place = (TextView) eventHeader.findViewById(R.id.event_full_info_place);
        place.setText(in.getStringExtra("place") + "\n" + in.getStringExtra("detail"));

        // 這部分來自TabActivity里面
        final Context context = EventActivity.this;

        String cacheDownloadPath = BmobPro.getInstance(context).getCacheDownloadDir() + "/" + PicfileName;
        String[] name = PicfileName.split("\\.");
        String newFileName = name[0] + "_3_300_0_100." + name[1];
        String cacheThumbnailPath = BmobPro.getInstance(context).getCacheThumbnailDir() + "/" + newFileName;

        /*if ((new File(cacheDownloadPath)).exists()) { // 判断是否存在文件

            if ((new File(cacheThumbnailPath)).exists()) { // 判断是否存在缓存

                Log.i("bmob", "成功加载缓存：" + cacheThumbnailPath);
                Bitmap bm = BitmapFactory.decodeFile(cacheThumbnailPath);
                //photo.setImageBitmap(bm);
                mImageView.setImageBitmap(bm);
                String str = BmobPro.getInstance(context).getCacheDownloadDir();
                Log.i("bmob", str);

            } else {    // 缓存不存在则重新生成缓存
                BmobProFile.getInstance(context).getLocalThumbnail(cacheDownloadPath, 3, new LocalThumbnailListener() {

                    @Override
                    public void onSuccess(String thumbnailPath) {
                        Bitmap bm = BitmapFactory.decodeFile(thumbnailPath);
                        mImageView.setImageBitmap(bm);
                    }

                    @Override
                    public void onError(int statuscode, String errormsg) {
                    }
                });
            }

        } else { // 缓存不存在需要从远程下载
            BmobProFile.getInstance(context).download(PicfileName, new DownloadListener() {

                @Override
                public void onSuccess(String fullPath) {
                    BmobProFile.getInstance(context).getLocalThumbnail(fullPath, 3, new LocalThumbnailListener() {

                        @Override
                        public void onSuccess(String thumbnailPath) {
                            Log.i("bmob", "下载并生成成功：" + thumbnailPath);
                            Bitmap bm = BitmapFactory.decodeFile(thumbnailPath);
                            //photo.setImageBitmap(bm);
                            mImageView.setImageBitmap(bm);
                            String str = BmobPro.getInstance(context).getCacheDownloadDir();
                            Log.i("bmob", str);
                        }

                        @Override
                        public void onError(int statuscode, String errormsg) {
                        }
                    });
                    String str = BmobPro.getInstance(context).getCacheDownloadDir();
                    Log.i("bmob", str);
                }

                @Override
                public void onProgress(String localPath, int percent) {
                    Log.i("bmob", "download-->onProgress :" + percent);
                }

                @Override
                public void onError(int statuscode, String errormsg) {
                    Log.i("bmob", "下载出错：" + statuscode + "--" + errormsg);
                    Toast.makeText(context, "下载出错：" + statuscode + "--" + errormsg, Toast.LENGTH_SHORT).show();
                }
            });
        }*/
        if ((new File(cacheDownloadPath)).exists()) { // 判断是否存在文件

            Log.i("bmob", "成功加载缓存：" + cacheDownloadPath);
            Bitmap bm = BitmapFactory.decodeFile(cacheDownloadPath);
            //photo.setImageBitmap(bm);
            mImageView.setImageBitmap(bm);
            String str = BmobPro.getInstance(context).getCacheDownloadDir();
            Log.i("bmob", str);

        } else {

            BTPFileResponse response = BmobProFile.getInstance(context).download(PicfileName, new DownloadListener() {

                @Override
                public void onSuccess(String fullPath) {
                    // TODO Auto-generated method stub
                    Log.i("bmob", "下载成功：" + fullPath);
                    Bitmap bm = BitmapFactory.decodeFile(fullPath);
                    //photo.setImageBitmap(bm);
                    mImageView.setImageBitmap(bm);
                    String str = BmobPro.getInstance(context).getCacheDownloadDir();
                    Log.i("bmob", str);
                }

                @Override
                public void onProgress(String localPath, int percent) {
                    // TODO Auto-generated method stub
                    Log.i("bmob", "download-->onProgress :" + percent);
                }

                @Override
                public void onError(int statuscode, String errormsg) {
                    // TODO Auto-generated method stub
                    Log.i("bmob", "下载出错：" + statuscode + "--" + errormsg);
                    Toast.makeText(context, "下载出错：" + statuscode + "--" + errormsg, Toast.LENGTH_SHORT).show();
                }
            });
        }

        // 此处开始查询已加入的用户
        final LinearLayout userList = (LinearLayout) eventHeader.findViewById(R.id.event_user_list);
        BmobQuery<Involvement> bmobQuery = new BmobQuery<Involvement>();
        bmobQuery.addWhereEqualTo("activityId", in.getStringExtra("id"));
        bmobQuery.addQueryKeys("user");
        bmobQuery.include("user.objectId,user.nickname,user.picFileName,user.description");
        bmobQuery.order("createdAt");
        bmobQuery.setLimit(10);
        bmobQuery.findObjects(this, new FindListener<Involvement>() {
            @Override
            public void onSuccess(List<Involvement> object) {
                // TODO Auto-generated method stub
                Toast.makeText(EventActivity.this, "共" + object.size() + "人", Toast.LENGTH_SHORT);
                //注意：这里的Involvement对象中只有指定列的数据。

                for (Involvement inv : object) {
                    final User user = inv.getUser();

                    LayoutInflater inflater = LayoutInflater.from(EventActivity.this);
                    View singleUser = inflater.inflate(R.layout.listview_user_simple, null);
                    singleUser.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent();
                            intent.putExtra("username", user.getNickname());
                            intent.putExtra("userid", user.getObjectId());
                            intent.putExtra("userpicname", user.getPicFilename());
                            intent.putExtra("userdescription", user.getDescription());
                            intent.setClass(EventActivity.this, UserPageActivity.class);
                            startActivity(intent);
                        }
                    });
                    final CircleImageView userImage = (CircleImageView) singleUser.findViewById(R.id.user_simple_img);

                    // 获取头像文件名
                    String fileName = user.getPicFilename();

                    // 得到文件路径
                    String cacheDownloadPath = BmobPro.getInstance(context).getCacheDownloadDir() + "/" + fileName;
                    String[] name = fileName.split("\\.");
                    String newFileName = name[0] + "_1_200_0_100." + name[1];
                    String cacheThumbnailPath = BmobPro.getInstance(context).getCacheThumbnailDir() + "/" + newFileName;

                    if ((new File(cacheDownloadPath)).exists()) { // 判断是否存在文件

                        if ((new File(cacheThumbnailPath)).exists()) { // 判断是否存在缓存

                            Bitmap bm = BitmapFactory.decodeFile(cacheThumbnailPath);
                            userImage.setImageBitmap(bm);

                        } else { // 缓存不存在则重新生成缓存

                            BmobProFile.getInstance(context).getLocalThumbnail(cacheDownloadPath, 1, new LocalThumbnailListener() {

                                @Override
                                public void onSuccess(String thumbnailPath) {
                                    Bitmap bm = BitmapFactory.decodeFile(thumbnailPath);
                                    userImage.setImageBitmap(bm);
                                }

                                @Override
                                public void onError(int statuscode, String errormsg) {
                                }
                            });

                        }

                    } else { // 文件不存在需要重新下载

                        BmobProFile.getInstance(context).download(fileName, new DownloadListener() {

                            @Override
                            public void onSuccess(String fullPath) {
                                BmobProFile.getInstance(context).getLocalThumbnail(fullPath, 1, new LocalThumbnailListener() {

                                    @Override
                                    public void onSuccess(String thumbnailPath) {
                                        Bitmap bm = BitmapFactory.decodeFile(thumbnailPath);
                                        userImage.setImageBitmap(bm);
                                    }

                                    @Override
                                    public void onError(int statuscode, String errormsg) {
                                    }
                                });
                                String str = BmobPro.getInstance(context).getCacheDownloadDir();
                                Log.i("bmob", str);
                            }

                            @Override
                            public void onProgress(String localPath, int percent) {
                                Log.i("bmob", "download-->onProgress :" + percent);
                            }

                            @Override
                            public void onError(int statuscode, String errormsg) {

                            }
                        });
                    }
                    userList.addView(singleUser);
                }

                LayoutInflater inflater = LayoutInflater.from(EventActivity.this);
                View moreUser = inflater.inflate(R.layout.more_user, null);
                moreUser.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        intent.putExtra("input", ActiId);
                        intent.putExtra("mode", "participant");
                        intent.putExtra("title", "参与用户");
                        intent.setClass(EventActivity.this, UserList.class);
                        startActivity(intent);
                    }
                });
                userList.addView(moreUser);
            }

            @Override
            public void onError(int code, String msg) {
                Toast.makeText(EventActivity.this, "查询失败", Toast.LENGTH_SHORT);
            }
        });


        // 查询个人头像
        final CircleImageView userImage = (CircleImageView) findViewById(R.id.event_head_me);
        // User curUser = BmobUser.getCurrentUser(context, User.class);

        cacheDownloadPath = BmobPro.getInstance(context).getCacheDownloadDir() + "/" + curUser.getPicFilename();
        name = curUser.getPicFilename().split("\\.");
        newFileName = name[0] + "_1_200_0_100." + name[1];
        cacheThumbnailPath = BmobPro.getInstance(context).getCacheThumbnailDir() + "/" + newFileName;

        if ((new File(cacheDownloadPath)).exists()) { // 判断是否存在文件

            if ((new File(cacheThumbnailPath)).exists()) { // 判断是否存在缓存

                Bitmap bm = BitmapFactory.decodeFile(cacheThumbnailPath);
                userImage.setImageBitmap(bm);

            } else { // 缓存不存在则重新生成缓存

                BmobProFile.getInstance(context).getLocalThumbnail(cacheDownloadPath, 1, new LocalThumbnailListener() {

                    @Override
                    public void onSuccess(String thumbnailPath) {
                        Bitmap bm = BitmapFactory.decodeFile(thumbnailPath);
                        userImage.setImageBitmap(bm);
                    }

                    @Override
                    public void onError(int statuscode, String errormsg) {
                    }
                });

            }

        } else { // 文件不存在需要重新下载

            BmobProFile.getInstance(context).download(curUser.getPicFilename(), new DownloadListener() {

                @Override
                public void onSuccess(String fullPath) {
                    Log.i("bmob", "????????" + fullPath);
                    BmobProFile.getInstance(context).getLocalThumbnail(fullPath, 1, new LocalThumbnailListener() {

                        @Override
                        public void onSuccess(String thumbnailPath) {
                            Bitmap bm = BitmapFactory.decodeFile(thumbnailPath);
                            userImage.setImageBitmap(bm);
                        }

                        @Override
                        public void onError(int statuscode, String errormsg) {
                        }
                    });
                    String str = BmobPro.getInstance(context).getCacheDownloadDir();
                    Log.i("bmob", str);
                }

                @Override
                public void onProgress(String localPath, int percent) {
                    Log.i("bmob", "download-->onProgress :" + percent);
                }

                @Override
                public void onError(int statuscode, String errormsg) {

                }
            });
        }

        findViewById(R.id.comment_view).getViewTreeObserver()
                .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        FrameLayout.LayoutParams p = new FrameLayout.LayoutParams(
                                FrameLayout.LayoutParams.MATCH_PARENT,
                                FrameLayout.LayoutParams.MATCH_PARENT);
                        p.setMargins(0, mActionBarSize, 0, findViewById(R.id.comment_view).getHeight());
                        listView.setLayoutParams(p);
                    }
                });
    }

    public void loadComments(final LoadCommentsListener listener) {

        BmobQuery<Comment> query = new BmobQuery<Comment>();
        query.addWhereEqualTo("activityId", ActiId);
        query.order("-createdAt");
        query.setLimit(15);
        query.setSkip(page * 15);
        query.include("user.objectId,user.nickname,user.picFileName");

        query.findObjects(this, new FindListener<Comment>() {

            @Override
            public void onSuccess(List<Comment> object) {
                page++;
                for (Comment comment : object) {
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("comment", comment);
                    map.put("user", comment.getUser());
                    listItem.add(map);
                }
                if (listener == null) {
                    adapter = new CommentAdapter(EventActivity.this, listItem);
                    listView.setAdapter(adapter);

                } else {
                    hasNew = object.size() != 0;
                    adapter.notifyDataSetChanged();
                    listener.loadFinish(hasNew ? LoadMoreCommentsLayout.SUCCEED :
                            LoadMoreCommentsLayout.NOMORE, object.size());
                }
            }

            @Override
            public void onError(int code, String msg) {
                Toast.makeText(EventActivity.this, "下载失败，网络异常！", Toast.LENGTH_SHORT).show();
                if (listener != null) listener.loadFinish(LoadMoreCommentsLayout.FAIL, 0);
            }
        });
    }

    class CommentAdapter extends BaseAdapter {

        private LayoutInflater mInflater;
        private ArrayList<HashMap<String, Object>> list;
        private Context context;

        public CommentAdapter(Context context, ArrayList<HashMap<String, Object>> list) {
            this.mInflater = LayoutInflater.from(context);
            this.list = list;
            this.context = context;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            final CommentViewHolder holder;
            Log.v("MyListViewBase", "getView " + position + " " + convertView);
            if (convertView == null) {

                convertView = mInflater.inflate(R.layout.comment_item, null);
                holder = new CommentViewHolder();

                holder.content = (TextView) convertView.findViewById(R.id.comment_item_content);
                holder.user = (TextView) convertView.findViewById(R.id.comment_item_username);
                holder.date = (TextView) convertView.findViewById(R.id.comment_item_date);
                holder.image = (CircleImageView) convertView.findViewById(R.id.comment_item_userhead);

                convertView.setTag(holder);
            } else {
                holder = (CommentViewHolder) convertView.getTag();
            }

            holder.image.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    Intent intent = new Intent();
                    intent.putExtra("username", ((User) list.get(position).get("user")).getNickname());
                    intent.putExtra("userid", ((User) list.get(position).get("user")).getObjectId());
                    intent.putExtra("userpicname", ((User) list.get(position).get("user")).getPicFilename());
                    intent.putExtra("userdescription", ((User) list.get(position).get("user")).getDescription());
                    intent.setClass(EventActivity.this, UserPageActivity.class);
                    startActivity(intent);
                }
            });

            holder.content.setText(((Comment) list.get(position).get("comment")).getContent());
            holder.user.setText(((User) list.get(position).get("user")).getNickname());
            holder.date.setText(((Comment) list.get(position).get("comment")).getCreatedAt());

            String fileName = ((User) list.get(position).get("user")).getPicFilename();
            String cacheDownloadPath = BmobPro.getInstance(context).getCacheDownloadDir() + "/" + fileName;
            String[] name = fileName.split("\\.");
            String newFileName = name[0] + "_1_200_0_100." + name[1];
            String cacheThumbnailPath = BmobPro.getInstance(context).getCacheThumbnailDir() + "/" + newFileName;

            if ((new File(cacheDownloadPath)).exists()) {

                if ((new File(cacheThumbnailPath)).exists()) {

                    Bitmap bm = BitmapFactory.decodeFile(cacheThumbnailPath);
                    holder.image.setImageBitmap(bm);

                } else {

                    BmobProFile.getInstance(context).getLocalThumbnail(cacheDownloadPath, 1, new LocalThumbnailListener() {

                        @Override
                        public void onSuccess(String thumbnailPath) {
                            Log.i("bmob", "localThumbnail--> :" + thumbnailPath);
                            Bitmap bm = BitmapFactory.decodeFile(thumbnailPath);
                            holder.image.setImageBitmap(bm);
                        }

                        @Override
                        public void onError(int statuscode, String errormsg) {
                            Log.i("bmob", "localThumbnail--> :" + statuscode + "," + errormsg);
                        }
                    });

                }

            } else {

                BmobProFile.getInstance(context).download(fileName, new DownloadListener() {

                    @Override
                    public void onSuccess(String fullPath) {
                        BmobProFile.getInstance(context).getLocalThumbnail(fullPath, 1, new LocalThumbnailListener() {

                            @Override
                            public void onSuccess(String thumbnailPath) {
                                Bitmap bm = BitmapFactory.decodeFile(thumbnailPath);
                                holder.image.setImageBitmap(bm);
                            }

                            @Override
                            public void onError(int statuscode, String errormsg) {
                            }
                        });
                        String str = BmobPro.getInstance(context).getCacheDownloadDir();
                        Log.i("bmob", str);
                    }

                    @Override
                    public void onProgress(String localPath, int percent) {
                        Log.i("bmob", "download-->onProgress :" + percent);
                    }

                    @Override
                    public void onError(int statuscode, String errormsg) {
                    }
                });
            }
            return convertView;
        }
    }

    private boolean isTransp = true;

    @Override
    public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {

        this.scrollY = scrollY;

        if (scrollY > mFlexibleSpaceImageHeight - mActionBarSize) {
            if (isTransp) {
                ViewPropertyAnimator.animate(mOverlayView).cancel();
                ViewPropertyAnimator.animate(mOverlayView).alpha(1.0f).setDuration(200).start();
                isTransp = false;

                ((Toolbar) findViewById(R.id.event_toolbar)).setTitle(getIntent().getStringExtra("title"));
            }
            scrollY = mFlexibleSpaceImageHeight - mActionBarSize;
        } else if (!isTransp) {
            ViewPropertyAnimator.animate(mOverlayView).cancel();
            ViewPropertyAnimator.animate(mOverlayView).alpha(0.0f).setDuration(200).start();
            isTransp = true;

            ((Toolbar) findViewById(R.id.event_toolbar)).setTitle(null);
        } else {
            ((Toolbar) findViewById(R.id.event_toolbar)).setTitle(null);
        }

        if (listView.getLastVisiblePosition() == listView.getCount() - 1) {
            int lastIndex = listView.getLastVisiblePosition() - listView.getFirstVisiblePosition();
            View lastItem = listView.getChildAt(lastIndex);
            int height = lastItem.getMeasuredHeight();
            int location[] = new int[2];
            lastItem.getLocationInWindow(location);
            int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
            isBottom = location[1] <= screenHeight - height - findViewById(R.id.comment_view).getHeight();
        } else isBottom = false;

        // Translate overlay and image
        float flexibleRange = mFlexibleSpaceImageHeight - mActionBarSize;
        int minOverlayTransitionY = mActionBarSize - mOverlayView.getHeight();
        ViewHelper.setTranslationY(mOverlayView, ScrollUtils.getFloat(-scrollY, minOverlayTransitionY, 0));
        ViewHelper.setTranslationY(mImageView, ScrollUtils.getFloat(-scrollY / 2, minOverlayTransitionY, 0));

        // Translate list background
        ViewHelper.setTranslationY(mListBackgroundView, Math.max(0, -scrollY + mFlexibleSpaceImageHeight));

        // Translate FAB
        int maxFabTranslationY = mFlexibleSpaceImageHeight - mFab.getHeight() / 2;
        float fabTranslationY = ScrollUtils.getFloat(
                -scrollY + mFlexibleSpaceImageHeight - mFab.getHeight() / 2,
                mActionBarSize - mFab.getHeight() / 2,
                maxFabTranslationY);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            // On pre-honeycomb, ViewHelper.setTranslationX/Y does not set margin,
            // which causes FAB's OnClickListener not working.
            FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mFab.getLayoutParams();
            lp.leftMargin = mOverlayView.getWidth() - mFabMargin - mFab.getWidth();
            lp.topMargin = (int) fabTranslationY;
            mFab.requestLayout();
        } else {
            ViewHelper.setTranslationX(mFab, mOverlayView.getWidth() - mFabMargin - mFab.getWidth());
            ViewHelper.setTranslationY(mFab, fabTranslationY);
        }

        // Show/hide FAB
        if (fabTranslationY < mFlexibleSpaceShowFabOffset) {
            hideFab();
        } else {
            showFab();
        }
    }

    @Override
    public void onDownMotionEvent() {
    }

    @Override
    public void onUpOrCancelMotionEvent(ScrollState scrollState) {
    }

    private void showFab() {
        if (!mFabIsShown) {
            ViewPropertyAnimator.animate(mFab).cancel();
            ViewPropertyAnimator.animate(mFab).scaleX(1).scaleY(1).setDuration(200).start();
            mFabIsShown = true;
        }
    }

    private void hideFab() {
        if (mFabIsShown) {
            ViewPropertyAnimator.animate(mFab).cancel();
            ViewPropertyAnimator.animate(mFab).scaleX(0).scaleY(0).setDuration(200).start();
            mFabIsShown = false;
        }
    }


    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        LoadCommentTask task = new LoadCommentTask(this, null);
        task.execute();
    }

    class LoadCommentTask extends AsyncTask<Void, Integer, Integer> {

        private Context context;
        private LoadCommentsListener listener;

        public LoadCommentTask(Context context, LoadCommentsListener listener) {
            this.context = context;
            this.listener = listener;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {

            BmobQuery<Comment> query = new BmobQuery<Comment>();
            query.addWhereEqualTo("activityId", ActiId);
            query.order("-createdAt");
            query.setLimit(15);
            query.setSkip(page * 15);
            query.include("user.objectId,user.nickname,user.picFileName");

            query.findObjects(context, new FindListener<Comment>() {

                @Override
                public void onSuccess(List<Comment> object) {
                    page++;
                    for (Comment comment : object) {
                        HashMap<String, Object> map = new HashMap<String, Object>();
                        map.put("comment", comment);
                        map.put("user", comment.getUser());
                        listItem.add(map);
                    }
                    if (listener == null) {
                        adapter = new CommentAdapter(EventActivity.this, listItem);
                        listView.setAdapter(adapter);

                    } else {
                        hasNew = object.size() != 0;
                        adapter.notifyDataSetChanged();
                        listener.loadFinish(hasNew ? LoadMoreCommentsLayout.SUCCEED : LoadMoreCommentsLayout.NOMORE, object.size());
                    }
                }

                @Override
                public void onError(int code, String msg) {
                    Toast.makeText(EventActivity.this, "下载失败，网络异常！", Toast.LENGTH_SHORT).show();
                    if (listener != null) listener.loadFinish(LoadMoreCommentsLayout.FAIL, 0);
                }
            });
            return null;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {

        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }
}

class CommentViewHolder {
    public CircleImageView image;
    public TextView content;
    public TextView date;
    public TextView user;
}

/**
 * 刷新加载回调接口
 *
 * @author chenjing
 */
interface OnLoadCommentsListener {

    void onRefresh(LoadMoreCommentsLayout loadMoreCommentsLayout);

    /**
     * 加载操作
     */
    void onLoadMore(LoadMoreCommentsLayout loadMoreCommentsLayout);
}

class LoadCommentsListener implements OnLoadCommentsListener {

    private Context mContext;
    private LoadMoreCommentsLayout loadMoreCommentsLayout;

    public LoadCommentsListener(Context mContext) {
        this.mContext = mContext;
    }

    @Override
    public void onRefresh(final LoadMoreCommentsLayout loadMoreCommentsLayout) {
    }

    @Override
    public void onLoadMore(LoadMoreCommentsLayout loadMoreCommentsLayout) {
        this.loadMoreCommentsLayout = loadMoreCommentsLayout;
        ((EventActivity) mContext).loadComments(this);
    }

    public void loadFinish(int code, int num) {
        loadMoreCommentsLayout.loadmoreFinish(code, num);
    }
}

